package com.training.controller;

import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.training.dto.AddressParamDto;
import com.training.dto.SupervisionDataDto;
import com.training.entity.Address;
import com.training.entity.NativeMap;
import com.training.entity.PublicSurveillanceData;
import com.training.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/publicFeedback")
@Tag(name = "公众监督反馈")
public class PublicFeedbackController {

    @GetMapping("/History/{id}")
    @Operation(summary = "历史反馈数据综合查询")
    public SaResult getHistoryData(@RequestParam(defaultValue = "1")Integer page,
                                   @RequestParam(defaultValue = "10")Integer pageSize,
                                   @RequestParam(defaultValue = "")String province,
                                   @RequestParam(defaultValue = "")String city,
                                   @RequestParam(defaultValue = "0")Integer estimatedLevel,
                                   @PathVariable(name = "id") String supervisorId,
                                   LocalDateTime startTime, LocalDateTime endTime) {
        List<PublicSurveillanceData> data;
        boolean b = Objects.isNull(startTime) || Objects.isNull(endTime);
        if (estimatedLevel == 0){
            if (b) {
                data = Db.lambdaQuery(PublicSurveillanceData.class)
                        .eq(PublicSurveillanceData::getSupervisorId, supervisorId)
                        .orderByAsc(PublicSurveillanceData::getFeedbackTime)
                        .list();
            } else {
                data = Db.lambdaQuery(PublicSurveillanceData.class)
                        .eq(PublicSurveillanceData::getSupervisorId, supervisorId)
                        .between(PublicSurveillanceData::getFeedbackTime, startTime.toLocalDate(), endTime.toLocalDate())
                        .orderByAsc(PublicSurveillanceData::getFeedbackTime)
                        .list();
            }
        } else {
            if (b) {
                data = Db.lambdaQuery(PublicSurveillanceData.class)
                        .eq(PublicSurveillanceData::getSupervisorId, supervisorId)
                        .eq(PublicSurveillanceData::getEstimatedLevel, estimatedLevel)
                        .orderByAsc(PublicSurveillanceData::getFeedbackTime)
                        .list();

            } else {
                data = Db.lambdaQuery(PublicSurveillanceData.class)
                        .eq(PublicSurveillanceData::getSupervisorId, supervisorId)
                        .eq(PublicSurveillanceData::getEstimatedLevel, estimatedLevel)
                        .between(PublicSurveillanceData::getFeedbackTime, startTime.toLocalDate(), endTime.toLocalDate())
                        .orderByAsc(PublicSurveillanceData::getFeedbackTime)
                        .list();
            }
        }

        // 筛选出province和city相同的数据
        data = data.stream().filter(e -> {
            Address address = Db.lambdaQuery(Address.class).eq(Address::getId, e.getFeedbackAddressId())
                    .like(Address::getProvince, province).like(Address::getCity, city).one();
            return Objects.nonNull(address);
        }).toList();

        List<SupervisionDataDto> supervisionDataDtos = data.stream().map(e -> {
            Address oneAddress = Db.lambdaQuery(Address.class).eq(Address::getId, e.getFeedbackAddressId()).one();
            User supervisor = Db.getById(e.getSupervisorId(), User.class);
            return SupervisionDataDto.builder()
                    .id(e.getId())
                    .supervisor(supervisor)
                    .address(oneAddress)
                    .description(e.getDescription())
                    .estimatedLevel(e.getEstimatedLevel())
                    .feedbackTime(e.getFeedbackTime())
                    .isAssigned(e.getIsAssigned())
                    .build();
        }).toList();
        //手动分页，筛选supervisionDataDtos
        int start = (page - 1) * pageSize;
        int end = Math.min(page * pageSize, supervisionDataDtos.size());
        supervisionDataDtos = supervisionDataDtos.subList(start, end);
        Map<String, Object> returnMap = Map.of("total", supervisionDataDtos.size(), "data", supervisionDataDtos);
        return SaResult.data(returnMap);
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "根据id获取历史数据")
    public SaResult getSupervisionDataById(@PathVariable String id) {
        PublicSurveillanceData data = Db.lambdaQuery(PublicSurveillanceData.class).eq(PublicSurveillanceData::getId, id).one();
        Address address = Db.lambdaQuery(Address.class).eq(Address::getId, data.getFeedbackAddressId()).one();
        User supervisor = Db.lambdaQuery(User.class).eq(User::getId, data.getSupervisorId()).one();
        SupervisionDataDto supervisionDataDto = SupervisionDataDto.builder()
                .id(data.getId())
                .supervisor(supervisor)
                .description(data.getDescription())
                .address(address)
                .estimatedLevel(data.getEstimatedLevel())
                .feedbackTime(data.getFeedbackTime())
                .isAssigned(data.getIsAssigned())
                .build();
        return SaResult.data(supervisionDataDto);
    }


    @PostMapping("/addPublic")
    public SaResult addPublic(@RequestBody AddressParamDto param) {
        Address address = new Address();
        NativeMap data1 = Db.lambdaQuery(NativeMap.class).eq(NativeMap::getCityCode, param.getCity()).one();
        address.setProvince(data1.getProvince());
        address.setCity(data1.getCity());
        address.setDetailedAddress(param.getAddress());
        Db.save(address);

        PublicSurveillanceData data = new PublicSurveillanceData();
        data.setIsAssigned(0);
        data.setEstimatedLevel(Integer.parseInt(param.getGrade()));
        data.setFeedbackAddressId(address.getId());
        data.setFeedbackTime(LocalDateTime.now());
        data.setDescription(param.getInfo());
        data.setSupervisorId(param.getJdyId());
        Db.save(data);
        return SaResult.ok("添加成功");
    }
}
